# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
import json
from decimal import *

def get_min_qty(base):
  dic = {"ETH": 0.001, "AAVE": 0.02287, "BTC": 0.00002, "PAXG": 0.005,  "USDC":1, "XRP":0.1, "ADA":0.1,
         "DOGE": 0.01, "SOL":0.01, "SHIB":200000, "DOT":0.01, "ATOM": 0.01, "ICP": 0.01, "AXAX": 0.01, "ALGO":0.01,
         "XTZ":0.01, "XLM":2, "WEMIX": 0.5128
         }
  if base in dic:
    return dic[base]
  
  return 0

def get_min_amount(base):
  dic = {"ADA": 0.8}
  if base in dic:
    return dic[base]

  return 0
  
def generate():
  mea = 'Spot.Mercado.v4'
  me = 'Spot.Mercado'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.mercadobitcoin.net/api/v4/symbols", proxies={'https':'socks5://127.0.0.1:9999'}, timeout=3)
  data = data.json()
  count = len(data["symbol"])
  item_list = [{} for i in range(count)]
  for key , val in data.items():
    for i in range(0, count):
      item_list[i][key] = val[i]
  
  pis = []
  for info in item_list:
    if info['exchange-listed'] is not True:
      continue
    
    native_symbol = info['symbol']
    native_base = info['base-currency']
    native_quote = info['currency']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    price_precision = float(Decimal("1") / Decimal(info['pricescale']))
    min_qty = get_min_qty(native_base)
    min_amount = get_min_amount(base)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=price_precision,
        qty_ticksize=1e-8,
        min_qty=min_qty,
        min_amount = min_amount
    )
    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = [info['native_quote'].upper() for info in data]
  base_currency_list = [info['native_base'].upper() for info in data]
  currency_list = base_currency_list + quote_currency_list
  res = {
      'symbol_list': list(set(symbol_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'currency_list': list(set(currency_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
